<template>
	<view class="content">
		<uni-nav-bar shadow color="#000" background-color="#ffffff" status-bar left-icon="left" right-icon="more-filled"
			title="我的信箱" @clickLeft="back" @clickRight="back" />
		<view class="container">
			<uni-segmented-control class="control" :current="current" :values="items" @clickItem="onClickItem"
				styleType="text" activeColor="#ffffff">
			</uni-segmented-control>
			<view class="content">
				<view v-show="current === 0">
					<view v-if="myLetters.length > 0">
						<view v-for="(letter, index) in myLetters" :key="index" class="group"
							@click="onClickMyself(letter)">
							<view class="treeholeitem treeholelist__item ">
								<view class="treeholeitem_band"></view>
								<view class="treeholeitem_main">
									<text>亲爱的陌生人\n</text>
									<text style="margin-left: 30px;">你好！</text>
									<text class="treeholecontent treeholecontent_content "
										style="text-indent: 30px;">{{ letter.content }}</text>
									<view class="treeholeitem_person fw-medium">
										<image v-if="letter.avatar" :src="letter.avatar" mode="aspectFit"></image>
										{{ letter.sign }}
									</view>
									<view class="treeholeitem_time">
										{{ letter.timestamp | formatDate }}
									</view>
								</view>
								<view class="treeholeitem_footer">
									<view class="treeholeitem_op">
										<view class="treeholeitem_op-btn is-comment">
											留言(0)
										</view>
										<view class="treeholeitem_op-btn is-like">
											抱抱(0)
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view v-else class="nomore">
						- 已到底 -
					</view>
				</view>
				<view v-show="current === 1">
					<view v-if="receivedLetters.length > 0">
						<view v-for="(letter, index) in receivedLetters" :key="index" class="group"
							@click="onClickOthers(letter)">
							<view class="treeholeitem treeholelist__item ">
								<view class="treeholeitem_band"></view>
								<view class="treeholeitem_main">
									<text>亲爱的陌生人\n</text>
									<text style="margin-left: 30px;">你好！</text>
									<text class="treeholecontent treeholecontent_content "
										style="text-indent: 30px;">{{ letter.content }}</text>
									<view class="treeholeitem_person fw-medium">
										<image v-if="letter.avatar" :src="letter.avatar" mode="aspectFit"></image>
										{{ letter.sign }}
									</view>
									<view class="treeholeitem_time">
										{{ letter.timestamp | formatDate }}
									</view>
								</view>
								<view class="treeholeitem_footer">
									<view class="treeholeitem_op">
										<view class="treeholeitem_op-btn is-comment">
											留言(0)
										</view>
										<view class="treeholeitem_op-btn is-like">
											抱抱(0)
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view v-else class="nomore">
						- 已到底 -
					</view>
				</view>
			</view>
		</view>
		<view class="container2">
			<view class="buttonOpenApp" @click="handleOpenAppCilck()">
				<text class="wenzi2">打开APP，向树洞说说你的心事 </text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				items: ['我写的', '我拆的'],
				current: 0,
				myLetters: [], // 我写的信件
				receivedLetters: [], // 我拆的信件
				requestedLetterIds: {} // 用于存储已经请求过的信件Id
			};
		},
		filters: {
			formatDate(value) {
				const date = new Date(value);
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
			}
		},
		mounted() {
			this.fetchLetters(this.current);
		},
		methods: {
			handleOpenAppCilck() {
				console.log('打开下载app');
				window.open('https://sj.qq.com/appdetail/com.wwyy.wzhxl?ckey=CK1456487930531&from_wxz=1', '_blank');
			},
			fetchLetters(index) {
			        let url = '';
			        let userId = uni.getStorageSync('userId');
			        console.log('userid', userId); // 检查 userId 是否存在
			
			        if (!userId) {
			            uni.showToast({
			                title: '用户ID不存在，请登录',
			                icon: 'none'
			            });
			            return;
			        }
			
			        if (index === 0) {
			            url = `http://localhost:8080/letter/messages/my-list?userId=${userId}`;
			        } else {
			            // 从本地存储中获取拆开的信件ID
			            let openedLetterIds = uni.getStorageSync('openedLetterIds') || [];
			            console.log('Fetching received letters with IDs:', openedLetterIds);
			
			            openedLetterIds.forEach(async (messageID) => {
			                if (!this.requestedLetterIds[messageID]) { // 检查是否已经请求过
			                    try {
			                        const response = await new Promise((resolve, reject) => {
			                            uni.request({
			                                url: `http://localhost:8080/letter/messages/${messageID}`,
			                                method: 'GET',
			                                success: (res) => {
			                                    resolve(res);
			                                },
			                                fail: (err) => {
			                                    reject(err);
			                                }
			                            });
			                        });
			
			                        if (response.statusCode === 200) {
			                            // 合并到已有的收到的信件列表中，避免重复
			                            const newLetter = {
			                                ...response.data,
			                                timestamp: new Date(response.data.creationTime)
			                            };
			                            const index = this.receivedLetters.findIndex(l => l.messageID === messageID);
			                            if (index === -1) {
			                                this.receivedLetters.push(newLetter);
			                            }
			                            this.requestedLetterIds[messageID] = true; // 标记为已请求
			                        } else if (response.statusCode === 404) {
			                            console.warn(`Letter with ID ${messageID} not found.`);
			                        } else {
			                            console.error('Failed to fetch letter:', response);
			                        }
			                    } catch (error) {
			                        console.error('Error fetching letter:', error);
			                    }
			                }
			            });
			        }
			
			        // 请求“我写的”信件
			        if (url) {
			            uni.request({
			                url: url,
			                method: 'GET',
			                success: (res) => {
			                    console.log('Response from server:', res); // 检查服务器响应
			                    if (res.statusCode === 200 && res.data.code === 200 && Array.isArray(res.data.rows)) {
			                        console.log('Received valid data:', res.data.rows); // 检查接收到的有效数据
			                        if (index === 0) {
			                            this.myLetters = res.data.rows.map(letter => ({
			                                ...letter,
			                                timestamp: new Date(letter.creationTime)
			                            }));
			                        }
			                    } else {
			                        console.error('Invalid data received:', res.data); // 检查无效数据
			                        uni.showToast({
			                            title: '数据无效，请刷新页面',
			                            icon: 'none'
			                        });
			                    }
			                },
			                fail: (err) => {
			                    console.error('Network request failed:', err); // 检查网络请求失败
			                    uni.showToast({
			                        title: '网络请求失败，请稍后重试',
			                        icon: 'none'
			                    });
			                }
			            });
			        }
			    },
			onClickItem(e) {
				if (this.current !== e.currentIndex) {
					this.current = e.currentIndex;
					this.fetchLetters(this.current);
				}
			},
			onClickMyself(letter) {
				console.log(`跳转我写的`, letter);
				uni.redirectTo({
					url: `/pages/myself-write/myself-write?messageId=${letter.messageID}`
				});
			},
			onClickOthers(letter) {
				console.log(`跳转他人写的`, letter);
				uni.redirectTo({
					url: `/pages/otherletter/otherletter?messageId=${letter.messageID}`
				});
			},
			back() {
				console.log("返回");
				uni.redirectTo({
					url: '/pages/index/index'
				})
			}
		}
	}
</script>

<style lang="scss">
	.container {
		position: relative;
		background-image: url();
		background-size: cover;
		/* 保持图像的宽高比，覆盖整个容器的宽度 */
		background-position: center bottom;
		/* 将图像的底部居中对齐 */
		background-repeat: no-repeat;
		background-attachment: fixed;
		height: calc(100vh - 100px);
		overflow-y: auto;
	}

	.container2 {
		position: fixed;
		/* 或者使用 sticky */
		bottom: 0;
		width: 100%;
	}

	.buttonOpenApp {
		margin: 20rpx auto;
		display: flex;

		align-items: center;
		justify-content: center;
		width: 700rpx;
		height: 50px;
		border-radius: 30px;
		background-color: #ffca85;

	}

	.wenzi2 {
		color: #000000;
		font-weight: bold;
		font-size: 18px;
	}

	.control {
		background-color: transparent;
		border: none;
	}

	.treeholeitem_band {
		position: relative;
		transform: skewX(-45deg);
		display: block;
		height: 4px;
		margin: 0 -8px;
		background-image: -webkit-gradient(linear, left top, right top, color-stop(21.4285%, rgba(0, 0, 0, 0)), color-stop(21.4285%, #f08181), color-stop(50%, #f08181), color-stop(50%, rgba(0, 0, 0, 0)), color-stop(71.4285%, rgba(0, 0, 0, 0)), color-stop(71.4285%, #7aafeb));
		background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, 0) 21.4285%, #f08181 0, #f08181 50%, rgba(0, 0, 0, 0) 0, rgba(0, 0, 0, 0) 71.4285%, #7aafeb 0);
		background-image: -o-linear-gradient(left, rgba(0, 0, 0, 0) 21.4285%, #f08181 21.4285%, #f08181 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0) 71.4285%, #7aafeb 71.4285%);
		background-image: linear-gradient(90deg, rgba(0, 0, 0, 0) 21.4285%, #f08181 0, #f08181 50%, rgba(0, 0, 0, 0) 0, rgba(0, 0, 0, 0) 71.4285%, #7aafeb 0);
		background-size: 58px 100%;
	}

	.treeholeitem_main {
		padding: 13px 19px;
		font-size: 15px;
		line-height: 23px;
	}

	.treeholelist__item {
		margin: 17px;
	}

	.treeholecontent_content {
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;

	}

	.treeholecontent {
		white-space: pre-wrap;
		word-break: break-all;
	}

	.treeholeitem {
		border-radius: 5px;
		color: #523d14;
		background-color: #fffbea;
		background-image: url();
		background-size: 86px auto;
		background-position: top 13px right -4px;

		box-shadow: 0 2px 4px 0 rgba(50, 39, 16, .3);
		overflow: hidden;
	}

	.treeholeitem,
	.wzhavatar {
		background-repeat: no-repeat;
	}

	.treeholeitem_person {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		text-align: right;
		margin: 12px 0 0;
	}

	.treeholeitem_time {
		margin: 5px 0 0;
		font-size: 12px;
		line-height: 1.05;
		text-align: right;
	}

	.fw-medium {
		font-weight: 600;
	}

	.treeholeitem_footer {
		position: relative;
		padding: 12px 14px;
	}

	.treeholeitem_footer:before {
		content: "";
		position: absolute;
		left: 14px;
		right: 14px;
		top: 0;
		height: 1px;
		background: linear-gradient(90deg, #e0cbab 0, #e0cbab 40%, rgba(0, 0, 0, 0) 0);
		background-size: 14px 100%;
	}

	.treeholeitem_op {
		-webkit-box-align: center;
		align-items: center;
		display: flex;
	}

	.treeholeitem_op-btn {
		display: inline-flex;
		font-size: 14px;
		line-height: 1.05;
		padding: 10px;
		margin: -6px;
		user-select: none;
		align-items: center;

	}

	.treeholeitem_op-btn+.treeholeitem_op-btn {

		margin-left: 13px;
	}

	.nomore {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 32px;
		font-size: 13px;
		overflow: hidden;
		color: var(--color-text-secondary, #999);
	}
</style>